import axios from 'axios'
import { getToken } from './token'
const baseUrl = '/api/'
import Nprogress from 'nprogress'

//请求拦截
axios.interceptors.request.use(function (config) {
  Nprogress.start()
  //在请求头中添加token
  config.headers.token = getToken() ? getToken().token : null
  return config
})

//响应拦截
axios.interceptors.response.use(function (res) {
  Nprogress.done()
  return res
})

const map = new Map()
map.set('get', get)
map.set('put', put)
map.set('delete', del)
map.set('post', post)

/*
options = {
  url: 'http://127.0.0.1:3009/users/login', //请求地址
  type: 'get',  //请求类型
  data: {name:'',pass''} //请求参数
}
*/
function request(options) {
  let type = options.type
  if (!type) {
    //直接抛出异常，让程序终止，此异常必须解决
    throw new Error('请指定使用POST,GET,DELETE,PUT方法')
  }
  return map.get(type.toLowerCase())(options)
}

async function get(options) {
  return await axios.get(baseUrl + options.url, { params: options.data })
}

async function del(options) {
  return await axios.delete(baseUrl + options.url, { params: options.data })
}

async function put(options) {
  return await axios.put(baseUrl + options.url, options.data)
}

async function post(options) {
  return await axios.post(baseUrl + options.url, options.data)
}

export { request }
